package process

import (
	"github.com/foolin/gomap"
	"github.com/foolin/gosupervisor"
)

func NewSupervisord(url string) *Supervisord {
	return &Supervisord{
		url:    url,
		client: gosupervisor.New(url),
	}
}

type Supervisord struct {
	url    string
	wait   bool
	client *gosupervisor.SupervisorRpc
}

func (r Supervisord) GetAPIVersion() string {
	version, err := r.client.GetAPIVersion()
	if err != nil {
		panic(err)
	}

	return version
}
func (r Supervisord) GetAllProcessInfo() []gomap.Mapx {
	items, err := r.client.GetAllProcessInfo()
	if err != nil {
		panic(err)
	}

	// for _, item := range items {
	// 	item.Get("name")
	// 	item.Get("description")
	// 	time.Unix(item.Int64("start", 0), 0)
	// }

	return items
}

func (r Supervisord) ReloadConfig() bool {
	result, err := r.client.ReloadConfig()
	if err != nil {
		panic(err)
	}

	return result
}
func (r Supervisord) Restart() bool {
	result, err := r.client.Restart()
	if err != nil {
		panic(err)
	}

	return result
}
func (r Supervisord) Shutdown() bool {
	result, err := r.client.Shutdown()
	if err != nil {
		panic(err)
	}

	return result
}
func (r Supervisord) StartProcess(name string) bool {
	result, err := r.client.StartProcess(name, true)
	if err != nil {
		panic(err)
	}

	return result
}
func (r Supervisord) StartProcessGroup(groupName string) []gomap.Mapx {
	result, err := r.client.StartProcessGroup(groupName, r.wait)
	if err != nil {
		panic(err)
	}

	return result
}
func (r Supervisord) StartAllProcess() []gomap.Mapx {
	result, err := r.client.StartAllProcess(r.wait)
	if err != nil {
		panic(err)
	}

	return result
}
func (r Supervisord) StopProcess(name string) bool {
	result, err := r.client.StopProcess(name, true)
	if err != nil {
		panic(err)
	}

	return result
}
func (r Supervisord) StopProcessGroup(groupName string) []gomap.Mapx {
	result, err := r.client.StopProcessGroup(groupName, r.wait)
	if err != nil {
		panic(err)
	}

	return result
}
func (r Supervisord) StopAllProcess() []gomap.Mapx {
	result, err := r.client.StopAllProcesses(r.wait)
	if err != nil {
		panic(err)
	}

	return result
}

// supervisord := NewSupervisord("http://127.0.0.1:9001/RPC2")
// supervisord.ReloadConfig()
